package work.soho.proxy.socket5;

import com.jcraft.jsch.*;
import java.io.InputStream;
import java.io.OutputStream;

public class StreamForwarding{
    /**
     * 执行stream转发
     *
     * @param host
     * @param port
     * @param user
     * @param password
     * @param in
     * @param out
     * @param targetHost
     * @param targetPort
     */
    public static void forwarding(String host, int port, String user, String password, InputStream in, OutputStream out, String targetHost, int targetPort){
        try{
            JSch jsch=new JSch();
            Session session=jsch.getSession(user, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            forwarding(session, in, out, targetHost, targetPort);
        } catch(Exception e){
            System.out.println(e);
        }
    }

    /**
     * 秘钥方式登录转发数据
     *
     * @param host
     * @param port
     * @param user
     * @param keyPath
     * @param in
     * @param out
     * @param targetHost
     * @param targetPort
     */
    public static void forwarding(String host, int port, String user, String keyPath,
                                  String keyPassword, InputStream in, OutputStream out, String targetHost,
                                  int targetPort){
        try{
            JSch jsch=new JSch();
            System.out.println("private key: " + keyPath);
            jsch.addIdentity(keyPath, keyPassword);
            Session session=jsch.getSession(user, host, port);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setTimeout(1000);
            session.connect();
            forwarding(session, in, out, targetHost, targetPort);
        } catch(Exception e){
            System.out.println(e);
        }
    }

    /**
     * 数据流转发
     *
     * @param session
     * @param in
     * @param out
     * @param targetHost
     * @param targetPort
     */
    public static void forwarding(Session session, InputStream in, OutputStream out, String targetHost, int targetPort){
        try{
            Channel channel = session.getStreamForwarder(targetHost, targetPort);
            channel.setInputStream(in);
            channel.setOutputStream(out);
            channel.connect(10000);
//            channel.thread.join();
        } catch(Exception e){
            System.out.println(e);
        }
    }

}